<script>
import { useArticleApi } from "@/api/homePage";
import HzSafeArea from "@/components/layout/hz/hz-safe-area.vue";
import HzWaterfall from "@/components/layout/hz/hz-waterfall.vue";
import HzWaterfallItem from "@/components/layout/hz/hz-waterfall-item.vue";
import navBar from "@/components/layout/navbar/index.vue";
import { mapState } from "vuex";
import Config from "@/config";
export default {
  name: "list",
  components: {
    navBar,
    HzSafeArea,
    HzWaterfall,
    HzWaterfallItem,
  },
  data() {
    return {
      imgUrl: Config.imgUrl,
      raidersList: [],
      isLoading: true,
      isLoadingMore: false,
      currentPage: 1,
      pageSize: 10,
      hasMore: true,
      isRefreshing: false,
      id: "",
      title: "",
    };
  },
  computed: {
    ...mapState({
      selectedLocation: (state) => state.base.selectedLocation,
    }),
    top() {
      return 44 + this.$store.state.app.wxMenuClient.top;
    },
  },
  onLoad(options) {
    if (options && options.id) {
      this.id = options.id;
      this.title = options.id === "3607" ? "旅游攻略" : "景点介绍";
      this.attractions = options.attractions === "true";
      // uni.setNavigationBarTitle({
      //   title: title
      // });
      this.loadData();
    }
  },
  // 启用下拉刷新
  onPullDownRefresh() {
    this.isRefreshing = true;
    this.currentPage = 1;
    this.hasMore = true;

    // 重置瀑布流组件
    if (this.$refs.waterfall) {
      this.$refs.waterfall.resetLoadmore();
    }

    this.loadData(true);
  },
  // 监听触底事件
  onReachBottom() {
    if (this.hasMore && !this.isLoadingMore) {
      this.loadMore();
    }
  },
  // 设置页面的原生配置
  config: {
    enablePullDownRefresh: true,
    onReachBottomDistance: 50,
    backgroundColor: "#F5F7FA",
  },
  // 页面配置 (app.json)
  // #ifdef MP
  navigationBarTitleText: "旅游攻略",
  enablePullDownRefresh: true,
  onReachBottomDistance: 50,
  backgroundColor: "#F5F7FA",
  // #endif
  methods: {
    // 加载数据
    async loadData(isRefresh = false) {
      if (!isRefresh) {
        uni.showLoading({
          title: "加载中...",
          mask: true,
        });
      }

      try {
        // 从store获取选中的位置
        const selectedLocation = this.$store.state.base.selectedLocation;

        // 构造请求参数
        const params = {
          ArticleCategoryId: this.id,
          Index: this.currentPage,
          Size: this.pageSize,
          AreaId: selectedLocation.value,
        };

        // 请求数据
        let { Data } = await useArticleApi(params);

        // 为每个数据项添加随机颜色
        if (Data && Data.length > 0) {
          const colors = [
            "#4AA1FF",
            "#FFF7E3",
            "#E3F7E9",
            "#FFB6C1",
            "#FFA500",
            "#C1B9A6",
          ];
          Data.forEach((item) => {
            item.color = colors[Math.floor(Math.random() * colors.length)];
            // 如果Tags存在，将其拆分成数组
            if (item.Tags) {
              item.tagsData = item.Tags.split(",").map((tag) => tag.trim());
            }

            // 当id为3607时，将Title和Abstract的值对调
            if (this.id === "3607") {
              const tempTitle = item.Title;
              item.Title = item.Abstract;
              item.Abstract = tempTitle;
            }
          });
        }

        // 判断是否还有更多数据
        this.hasMore = Data && Data.length === this.pageSize;

        // 更新数据
        if (this.currentPage === 1) {
          // 第一页数据，重置列表
          this.raidersList = Data || [];
        } else {
          // 追加数据
          this.raidersList = this.raidersList.concat(Data || []);
        }

        // 更新状态
        this.isLoading = false;
        this.isLoadingMore = false;

        if (isRefresh) {
          uni.stopPullDownRefresh();
          this.isRefreshing = false;
        } else {
          uni.hideLoading();
        }
      } catch (error) {
        console.error("获取攻略列表失败:", error);
        this.isLoading = false;
        this.isLoadingMore = false;
        this.isRefreshing = false;

        if (isRefresh) {
          uni.stopPullDownRefresh();
        } else {
          uni.hideLoading();
        }

        uni.showToast({
          title: "加载数据失败",
          icon: "none",
        });
      }
    },

    // 加载更多
    loadMore() {
      if (!this.hasMore || this.isLoadingMore) return;

      this.isLoadingMore = true;
      this.currentPage++;
      this.loadData();
    },

    // 点击攻略卡片
    handleItemClick(e) {
      const index = e.param;
      const item = this.raidersList[index];
      if (item) {
        this.goToDetail(item);
      }
    },

    // 跳转到详情页
    goToDetail(item) {
      if (this.attractions) {
        uni.navigateTo({
          url: `/mall_subpages/raiders/details?id=${item.Id}`,
        });
      } else if (this.id === "3607") {
        uni.navigateTo({
          url: `/pages/article/index?id=${item.Id}`,
        });
      } else {
        uni.navigateTo({
          url: `/pages/article/spotIntro?id=${item.Id}`,
        });
      }
    },

    // 监听瀑布流初始化完成事件
    onWaterfallInit(e) {
      console.log("瀑布流初始化完成:", e);
    },

    // 监听瀑布流排序完成事件
    onWaterfallEnd(e) {
      console.log("瀑布流排序完成:", e);
    },

    locationChanged() {
      // 重置页码和状态
      this.currentPage = 1;
      this.hasMore = true;
      this.isLoading = true;

      // 先清空列表
      this.raidersList = [];

      // 重置瀑布流组件
      if (this.$refs.waterfall) {
        this.$refs.waterfall.resetLoadmore();
      }

      // 重新加载数据
      this.loadData();
    },
  },
};
</script>

<template>
  <view class="container" :style="{ paddingTop: top + 'px' }">
    <nav-bar
      ref="navBarRef"
      fixed
      showHeaderIcon
      :title="title"
      :allowMaskClose="false"
      @locationChanged="locationChanged"
    />
    <!-- 骨架屏加载效果 -->
    <view class="skeleton-list" v-if="isLoading">
      <view class="skeleton-card" v-for="i in 4" :key="i">
        <view class="skeleton-image"></view>
        <view class="skeleton-info">
          <view class="skeleton-name"></view>
          <view class="skeleton-sort"></view>
        </view>
      </view>
    </view>

    <!-- 瀑布流攻略列表 -->
    <block v-if="!isLoading">
      <hz-waterfall
        ref="waterfall"
        v-if="raidersList.length > 0"
        :columnGap="20"
        :leftGap="30"
        :rightGap="30"
        :topGap="20"
        @init="onWaterfallInit"
        @end="onWaterfallEnd"
      >
        <hz-waterfall-item
          class="item-box"
          v-for="(item, index) in raidersList"
          :key="item.Id"
          :src="item.CoverImg"
          :param="index"
          :radius="12"
          :background="'#FFFFFF'"
          @click="handleItemClick"
        >
          <view
            class="raider-name"
            v-if="item.Title"
            :style="{ backgroundColor: item.color }"
            >@{{ item.Title }}</view
          >
          <view class="raider-info">
            <view v-if="item.Tags" class="raider-tags">
              <view
                v-for="tag in item.tagsData"
                :style="{ backgroundColor: item.color }"
                :key="tag"
                class="tag-item"
                >{{ tag }}</view
              >
            </view>
            <view v-if="item.Abstract" class="raider-abstract">{{
              item.Abstract
            }}</view>
            <view v-if="item.Address" class="raider-address">
              <image
                class="addressIcon"
                :src="imgUrl + 'upload/img/ws_static/static/traffic/adress.png'"
                mode="widthFix"
              ></image
              >{{ item.Address }}</view
            >
            <view class="raider-sort" v-if="item.Sort">
              <text class="sort-text">热度 {{ item.Sort }}</text>
            </view>
          </view>
        </hz-waterfall-item>
      </hz-waterfall>

      <!-- 空状态展示 -->
      <view class="empty-state" v-if="raidersList.length === 0">
        <image
          src="/static/images/empty.png"
          mode="aspectFit"
          class="empty-image"
        ></image>
        <text class="empty-text">暂无攻略信息</text>
      </view>

      <!-- 底部加载更多状态 -->
      <view class="load-more" v-if="raidersList.length > 0">
        <view class="loading" v-if="isLoadingMore">
          <view class="loading-icon"></view>
          <text class="loading-text">加载中...</text>
        </view>
        <text class="no-more" v-else-if="!hasMore">没有更多数据了</text>
      </view>
    </block>

    <HzSafeArea background="#F5F7FA"></HzSafeArea>
  </view>
</template>

<style scoped lang="scss">
.container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-top: 44px;
}

.header {
  margin-bottom: 40rpx;

  .title {
    font-size: 48rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }

  .subtitle {
    font-size: 28rpx;
    color: #666;
  }
}
.item-box {
  position: relative;
}
.raider-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  // line-height: 1.4;
  // display: -webkit-box;
  // -webkit-box-orient: vertical;
  // -webkit-line-clamp: 2;
  // overflow: hidden;
  position: absolute;
  left: 0;
  top: 50rpx;
  background-color: #c7ea87;
  box-sizing: border-box;
  padding: 5rpx 30rpx 5rpx 10rpx;
  border-bottom-right-radius: 30rpx;
  border-top-right-radius: 30rpx;
}
.raider-info {
  padding: 16rpx;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  .raider-address {
    width: 100%;
    display: flex;
    align-items: center;
    color: #666;
    font-size: 24rpx;
    .addressIcon {
      width: 80rpx;
      margin-right: 10rpx;
    }
  }
  .raider-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 10rpx;
    .tag-item {
      padding: 5rpx 10rpx;
      border-radius: 10rpx;
      font-size: 26rpx;
    }
  }
  .raider-sort {
    align-self: flex-start;
    background: rgba(255, 107, 49, 0.1);
    padding: 4rpx 12rpx;
    border-radius: 16rpx;

    .sort-text {
      font-size: 22rpx;
      color: #ff6b31;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 30rpx;

  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
  }

  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

/* 加载更多样式 */
.load-more {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80rpx;
  margin-top: 20rpx;
  padding-bottom: 30rpx;

  .loading {
    display: flex;
    align-items: center;

    .loading-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 12rpx;
      border: 3rpx solid #ddd;
      border-color: #ddd transparent transparent transparent;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    .loading-text {
      font-size: 26rpx;
      color: #999;
    }
  }

  .no-more {
    font-size: 26rpx;
    color: #999;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 骨架屏样式 */
.skeleton-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  padding: 0 30rpx;
}

.skeleton-card {
  background: #ffffff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.05);

  .skeleton-image {
    width: 100%;
    height: 240rpx;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 400% 100%;
    animation: shimmer 1.5s infinite;
  }

  .skeleton-info {
    padding: 16rpx;
    display: flex;
    flex-direction: column;
    gap: 8rpx;

    .skeleton-name {
      width: 100%;
      height: 28rpx;
      background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
      background-size: 400% 100%;
      animation: shimmer 1.5s infinite;
      border-radius: 4rpx;
    }

    .skeleton-sort {
      width: 80rpx;
      height: 24rpx;
      background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
      background-size: 400% 100%;
      animation: shimmer 1.5s infinite;
      border-radius: 16rpx;
    }
  }
}

@keyframes shimmer {
  0% {
    background-position: 100% 0;
  }

  100% {
    background-position: -100% 0;
  }
}
</style>